package com.zking.util;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

//主要负责连接和断开数据库
public class DBUtil {
	private static  final String DRIVERNAME="com.mysql.cj.jdbc.Driver";
	private static final String URL= "jdbc:mysql://8g253604x1.goho.co:42152/2024_xq";
	private static final String USER= "2024xq";
	private static final String PASSWORD= "123456";

	public static Connection getConnection() {
		try {
			Class.forName(DRIVERNAME);
			return DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void closeConnection(Connection conn,PreparedStatement pstmt,ResultSet set) {

		try {
			if(set != null) {
				set.close();
			}
			if(pstmt != null) {
				pstmt.close();
			}
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	//待完善--通用的增删改，查询
	//通用的增删改
	public static boolean update(String sql,Object... objs) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			for (int i = 0; i < objs.length; i++) {
				pstmt.setObject(i+1, objs[i]);
			};
			int result = pstmt.executeUpdate();
//			System.out.println(result);
			if(result > 0) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			closeConnection(conn,pstmt,null);
		}
		return false;
	}

	/**
	 * jdbc的封装可以用反射机制来封装,把从数据库中获取的数据封装到一个类的对象里
	 */
	public static <T> List<T> query(String sql, Class<T> cls, Object... params) {
		List<T> list = new ArrayList<T>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet set = null;

		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			if (params != null && params.length>0) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i+1, params[i]);
				}
			}
			set = pstmt.executeQuery();
			//封装数据:列名获得是关键
			ResultSetMetaData metaData = set.getMetaData();
			int len = metaData.getColumnCount();//得到列的个数
			while(set.next()){
				//获得参数中Class<T> cls对应的实体类的对象
				T objectInstance = cls.newInstance();

				for (int i = 0; i < len; i++) {
					String column_name = metaData.getColumnName(i+1);
					Object column_value = set.getObject(column_name);
//						System.out.println(column_name+"\t"+column_value);
					//把属性名和值，与对应的实体类进行关联
					Field field = cls.getDeclaredField(column_name);
					field.setAccessible(true);
					field.set(objectInstance, column_value);
				}
				list.add(objectInstance);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeConnection(conn,pstmt,null);
		}
		return list;
	}



}
